package org.greyhawk.samonitor.service;

import java.security.MessageDigest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("summaryGenerater")
@Scope(value="prototype")
public class Md5SummaryGenerater implements SummaryGenerater{
		
	private final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
         '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 
	
	@Override
	public String generateSummary(byte[] data) throws Exception{
		MessageDigest digest = MessageDigest.getInstance("MD5");
		if(data != null)
			digest.update(data);
		else
			return "";
		byte[] summary = digest.digest();
		return this.byteToHexString(summary);
	}
	
	
	private String byteToHexString(byte[] tmp) {
        String s;
        char str[] = new char[16 * 2]; 
        int k = 0; 
        for (int i = 0; i < 16; i++) { 
            byte byte0 = tmp[i]; 
            str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 
            str[k++] = hexDigits[byte0 & 0xf]; 
        }
        s = new String(str);
        return s;
    }
}
